package com.naja.auth2clientfirst.support;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames;
import org.springframework.security.oauth2.core.user.OAuth2UserAuthority;

import java.util.*;

/**
 * @auther wangjianying
 * @date 2023/12/25 17:24
 */
public class ExpandAuthorityMapper implements GrantedAuthoritiesMapper {
    ExpandUserAuthoritiesRepository userAuthoritiesRepository = ExpandUserAuthoritiesRepository.instance();

    /**
     * 此方式实现整合客户端权限的方式,不能动态调整,权限列表变更需要重新登录才会生效
     * @see FederatedAuthorityConfigurer
     */
    @Override
    public Collection<? extends GrantedAuthority> mapAuthorities(Collection<? extends GrantedAuthority> authorities) {
        if (false) {
            Collection<? extends GrantedAuthority> grantedAuthorities = appendCustomAuthorities(authorities);
            return grantedAuthorities;
        }
        return authorities;
    }

    public Collection<? extends GrantedAuthority> appendCustomAuthorities(Collection<? extends GrantedAuthority> authorities) {
        String sub = null;
        Collection<GrantedAuthority> result = new HashSet();
        for (GrantedAuthority authority : authorities) {
            result.add(authority);
            if (authority instanceof OAuth2UserAuthority) {
                OAuth2UserAuthority oAuth2UserAuthority = (OAuth2UserAuthority) authority;
                Map<String, Object> attributes = oAuth2UserAuthority.getAttributes();
                sub = (String) attributes.get(IdTokenClaimNames.SUB);
            }
        }
        if (sub != null) {
            List<String> userAuthoritiesRepositoryByName = userAuthoritiesRepository.findByName(sub);
            if (userAuthoritiesRepositoryByName != null) {
                for (String s : userAuthoritiesRepositoryByName) {
                    result.add(new SimpleGrantedAuthority(s));
                }
            }
        }
        return result;
    }

}
